import { defineStore } from "pinia";
import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo } from '@/api/user'
import { LoginFormType, UserInfo, LoginCb } from '@/types/user'

export const useUserStore = defineStore({
  id: 'user',
  persist: true,
  state() {
    return {
      id:1,
      token: getToken(),
      token_type: '',
      userInfo: {} as UserInfo,
      showLogoutDialog: false,
    };
  },
  actions: {
    login(payload: LoginFormType) {
      return new Promise((resolve, reject) => {
        login(payload)
          .then(res => {
            const { code, data } = res
            if(code === 200) {
              const { access_token, expires_in, token_type } = data as LoginCb
              this.token = access_token
              this.token_type = token_type
              setToken(access_token, expires_in)
              this.getUserInfo()
              resolve(access_token)
            }
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    getUserInfo() {
      return new Promise((resolve, reject) => {
        getInfo()
          .then(res => {
            const { code, data } = res
            if(code === 200) {
              this.userInfo = data as UserInfo
            }
            resolve(data)
          })
          .catch(err => {
            reject(err)
          })
      })
    },
    logout() {
      this.token = ''
      removeToken()
    },
    setShowLogoutDialog(data:boolean) {
      this.showLogoutDialog = data
    },
  },
  getters: {
    uid(): number{
      return this.userInfo.id
    }
  }
})